const app = getApp();

Page({
  data: {
    roles: [],          // 角色列表
    isLoading: false,   // 加载状态
    showRoleModal: false,// 角色弹窗
    isEditMode: false,  // 编辑模式
    formData: {         // 表单数据
      id: '',
      roleName: '',
      roleCode: '',
      description: ''
    },
    searchKey: ''       // 搜索关键词
  },

  onLoad() {
    this.checkLoginStatus();
    this.loadRolesList();
  },

  onShow() {
    if (this.data.roles.length > 0) {
      this.loadRolesList();
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({ url: '/pages/login/login' });
    }
  },

  // 加载角色列表（对接/api/roles/list）
  loadRolesList() {
    this.setData({ isLoading: true });
    const token = wx.getStorageSync('token');
    const { searchKey } = this.data;

    wx.request({
      url: app.globalData.baseUrl + '/api/roles/list',
      method: 'GET',
      header: { 'Authorization': `Bearer ${token}` },
      data: { keyword: searchKey },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.data.code === 200 && Array.isArray(res.data.data)) {
          this.setData({ roles: res.data.data });
        } else {
          wx.showToast({ title: res.data.msg || '加载角色失败', icon: 'none' });
        }
      },
      fail: () => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误，角色加载失败', icon: 'none' });
      }
    });
  },

  // 搜索角色
  searchRoles() {
    this.loadRolesList();
  },

  onSearchInput(e) {
    this.setData({ searchKey: e.detail.value });
  },

  // 弹窗控制
  showAddRoleModal() {
    this.setData({
      showRoleModal: true,
      isEditMode: false,
      formData: {
        id: '',
        roleName: '',
        roleCode: '',
        description: ''
      }
    });
  },

  showEditRoleModal(e) {
    const role = e.currentTarget.dataset.role;
    this.setData({
      showRoleModal: true,
      isEditMode: true,
      formData: {
        id: role.id,
        roleName: role.roleName,
        roleCode: role.roleCode,
        description: role.description || ''
      }
    });
  },

  hideRoleModal() {
    this.setData({ showRoleModal: false });
  },

  // 表单处理
  onFormInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`formData.${field}`]: e.detail.value });
  },

  // 提交表单
  submitRoleForm() {
    const { isEditMode, formData } = this.data;
    if (!formData.roleName.trim()) {
      wx.showToast({ title: '请输入角色名称', icon: 'none' });
      return;
    }
    if (!formData.roleCode.trim()) {
      wx.showToast({ title: '请输入角色编码', icon: 'none' });
      return;
    }

    isEditMode ? this.updateRole() : this.createRole();
  },

  // 新增角色
  createRole() {
    this.setData({ isLoading: true });
    const token = wx.getStorageSync('token');
    const { formData } = this.data;

    wx.request({
      url: app.globalData.baseUrl + '/api/roles/create',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        roleName: formData.roleName.trim(),
        roleCode: formData.roleCode.trim(),
        description: formData.description.trim() || null
      },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.data.code === 200) {
          wx.showToast({ title: '新增角色成功' });
          this.hideRoleModal();
          this.loadRolesList();
        } else {
          wx.showToast({ title: res.data.msg || '新增失败', icon: 'none' });
        }
      },
      fail: () => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误，新增失败', icon: 'none' });
      }
    });
  },

  // 编辑角色
  updateRole() {
    this.setData({ isLoading: true });
    const token = wx.getStorageSync('token');
    const { formData } = this.data;

    wx.request({
      url: app.globalData.baseUrl + '/api/roles/update',
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        id: formData.id,
        roleName: formData.roleName.trim(),
        description: formData.description.trim() || null
      },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.data.code === 200) {
          wx.showToast({ title: '编辑角色成功' });
          this.hideRoleModal();
          this.loadRolesList();
        } else {
          wx.showToast({ title: res.data.msg || '编辑失败', icon: 'none' });
        }
      },
      fail: () => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误，编辑失败', icon: 'none' });
      }
    });
  },

  // 删除角色
  confirmDeleteRole(e) {
    const roleId = e.currentTarget.dataset.id;
    const roleName = e.currentTarget.dataset.name;
    wx.showModal({
      title: '确认删除',
      content: `确定要删除角色「${roleName}」吗？`,
      confirmColor: '#f56c6c',
      success: (res) => {
        if (res.confirm) {
          this.deleteRole(roleId);
        }
      }
    });
  },

  deleteRole(roleId) {
    this.setData({ isLoading: true });
    const token = wx.getStorageSync('token');

    wx.request({
      url: `${app.globalData.baseUrl}/api/roles/delete/${roleId}`,
      method: 'DELETE',
      header: { 'Authorization': `Bearer ${token}` },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.data.code === 200) {
          wx.showToast({ title: '删除成功' });
          this.loadRolesList();
        } else {
          wx.showToast({ title: res.data.msg || '删除失败', icon: 'none' });
        }
      },
      fail: () => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误，删除失败', icon: 'none' });
      }
    });
  },

  stopPropagation() {}
});
    